package com.aube.mis.velocity;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;
import org.springframework.web.servlet.view.velocity.VelocityViewResolver;

/**
 * 自定义 Velocity 视图解析器.
 * 
 * @see VelocityLayoutView
 */
public class CustomVelocityViewResolver extends VelocityViewResolver {

    private static final Logger log = LoggerFactory.getLogger(CustomVelocityViewResolver.class);

	/** 符号_点 */
	private static final String MARK_DOT = ".";

	/** 符号_星号 */
	private static final String MARK_ASTERISK = "*";

	/** 视图映射中把星号替换为点号+星号(.*) */
	private static final String MARK_DOT_AND_ASTERISK = MARK_DOT + MARK_ASTERISK;

	/** PAGE的请求地址后缀 */
	private static final String VIEW_NAME_PAGE = ".page";
	
	/** PJAX PAGE的对应的布局路径 */
	private static final String EMPTY_LAYOUT = "layout/empty.vm";

	/** 布局键值. 默认为：layout */
	private String layoutKey;

	/** 内容视图键值. 默认为：screen_content */
	private String screenContentKey;

	/** 各个目录的视图映射 */
	private Map<String, String> mappings = new HashMap<String, String>();

	public void setLayoutKey(final String layoutKey) {
		this.layoutKey = layoutKey;
	}

	public void setScreenContentKey(final String screenContentKey) {
		this.screenContentKey = screenContentKey;
	}

	public void setMappings(Map<String, String> mappings) {
		this.mappings = mappings;
	}

	@Override
	protected Class<?> requiredViewClass() {
		return VelocityLayoutView.class;
	}

	@Override
	protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("using " + this.getClass().getName() + ". View name=" + viewName);
		}

		VelocityLayoutView view = (VelocityLayoutView) super.buildView(viewName);
		if (this.layoutKey != null) {
			view.setLayoutKey(this.layoutKey);
		}
		if (this.screenContentKey != null) {
			view.setScreenContentKey(this.screenContentKey);
		}

		// 如果发现是page后缀,使用EMPTY布局模板
		if (viewName.indexOf(VIEW_NAME_PAGE) >= 0) {
			view.setLayoutUrl(EMPTY_LAYOUT);
			return view;
		}

		// 需要包装layout
		if (!this.mappings.isEmpty()) {
			for (Map.Entry<String, String> entry : this.mappings.entrySet()) {
				// 获取正则表达式
				String mappingRegexp = StringUtils.replace(entry.getKey(), MARK_ASTERISK, MARK_DOT_AND_ASTERISK);
				// 匹配视图
				if (viewName.matches(mappingRegexp) || viewName.indexOf(mappingRegexp) >= 0) {
					view.setLayoutUrl(entry.getValue());
					break;
				}
			}
		}
		return view;
	}
}
